<script setup lang="tsx">
defineOptions({
  name: "orderReport"
});

import { ref, reactive, computed, nextTick, h } from "vue";
import { queryGasOrderReportList, queryGasDeviceCode, updateGasCheckItemRemark } from "@/api/modules/operation";
import { PxIcon } from "px-ui";
import { Edit } from "@px-ui/icons-vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import { useRouterStoreHook } from "@/store/modules/router";
import dayjs from "dayjs";

const routerStore = useRouterStoreHook();

const orderReportTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonTableKey = ref<string>(Math.random().toString(36).slice(2, 10));
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const tableData = ref<Array<any>>([]);
const agCloumns = ref<Array<CommonTable.TableCloumnsType>>([]);
const loading = ref<boolean>(false);
const dialogLoading = ref<boolean>(false);
const dialogVisible = ref<boolean>(false);

const remarkForm = reactive({
  id: "",
  reportRemark: ""
});

let defaultParams: any = {
  // templateId: 1,
  // 	任务类型(1-气瓶,2-酸桶,3-槽车充填)
  taskType: 1
};
let currentParams = ref<Record<string, any>>({});

const searchOption = ref<Array<CommonSearch.SearchOption>>([
  {
    label: "设备编号",
    key: "deviceCode",
    // value: "GC-HF-01",
    value: "",
    required: true,
    type: "select",
    remote: true,
    selectRemoteApi: queryGasDeviceCode,
    getParams: (eqpId: string) => {
      const { subject: className } = routerStore;
      const categoryIds = [90, 94, 98, 88, 101];
      // facCode   一期  FAC_83abf9   二期  FAC_93abf6
      const facCode = localStorage.getItem("facCode");
      const systemCodes = facCode === "FAC_83abf9" ? ["SCA6CC96"] : facCode === "FAC_93abf6" ? ["SCC3F1B9"] : [];
      return { eqpId, className, systemCodes, categoryIds };
    },
    mapOption: item => ({ ...item, label: item.eqpId, value: item.eqpId }),
    realKeys: ["gasName", "deviceCode"],
    mapReturnSearchParams: ({ systemName: gasName, eqpId: deviceCode }: any) => ({ gasName, deviceCode }),
    placeholder: "请输入设备编号",
    span: 5
  },
  {
    label: "Check Item",
    key: "contentDesc",
    value: "",
    type: "input",
    placeholder: "请输入Check Item",
    span: 5
  },
  {
    label: "时间",
    key: "dateTimeStart",
    realKeys: ["dateTimeStart", "dateTimeEnd"],
    value: [],
    type: "daterange",
    props: {
      disabledDate: (data: Date) => dayjs().valueOf() < dayjs(data).valueOf()
    },
    span: 5
  }
]);

const tableCloumns = computed(() => {
  const children: Array<CommonTable.TableCloumnsType> = [
    {
      label: "Check Item",
      prop: "checkItem",
      width: 260
    }
  ];
  children.push(...agCloumns.value);
  children.push({
    label: "备注",
    prop: "reportRemark",
    width: 200,
    render({ row }: any) {
      const flag = ref<boolean>(false);
      const style = ref<Record<string, any>>({ width: "100%", paddingRight: "6px", display: "flex", alignItems: "center", gap: "12px" });
      const onMouseOverHandler = () => {
        flag.value = true;
      };
      const onMouseLeaveHandler = () => {
        flag.value = false;
      };
      const editFn = () => {
        remarkForm.id = row.id;
        remarkForm.reportRemark = row.reportRemark;
        dialogVisible.value = true;
      };
      return () =>
        h(
          <div style={{ ...style.value }}>
            <PxIcon
              size={18}
              style={{ cursor: "pointer", color: flag.value ? "var(--px-color-primary-light-3)" : "var(--px-color-primary)" }}
              onMouseOver={onMouseOverHandler}
              onMouseLeave={onMouseLeaveHandler}
              onClick={editFn}
            >
              <Edit />
            </PxIcon>
            {!!row.reportRemark ? (
              <span style={{ flex: 1, width: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{row.reportRemark || ""}</span>
            ) : null}
          </div>
        );
    }
  });
  const item = {
    prop: "itemDtoList",
    renderHeader() {
      const title = `${currentParams.value?.deviceCode || ""} 气瓶更换工单报表`;
      return () => <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>{title}</div>;
    },
    children: []
  };
  item.children = children;
  const cloumns = [item];
  return cloumns;
});

const queryTableDataFn = async () => {
  loading.value = true;
  tableData.value.splice(0);
  const params = { ...defaultParams, ...currentParams.value };
  const res = await queryGasOrderReportList(params, () => {
    loading.value = false;
  });
  agCloumns.value.splice(0);
  tableData.value = res.map(item => {
    const { itemDec: checkItem = "", remark: reportRemark = "", dayResultList = [] } = item;
    const data = { ...item, checkItem, reportRemark };
    for (const index in dayResultList) {
      const prop = `item${index}`;
      data[prop] = dayResultList[index].result;
      if (Number(index) > agCloumns.value.length - 1) {
        const label = dayResultList[index].date;
        const width = 120;
        agCloumns.value.push({ label, prop, width });
      }
    }
    return data;
  });
  await nextTick();
  commonTableKey.value = Math.random().toString(36).slice(2, 10);
  await nextTick();
  loading.value = false;
};

const submitSearchFormHandler = async (form: any) => {
  currentParams.value = { ...currentParams.value, ...form };
  await queryTableDataFn();
};

const resetSearchFormHandler = async () => {
  currentParams.value = {};
  await queryTableDataFn();
};

const submitFormHandler = async () => {
  dialogLoading.value = true;
  const res = await updateGasCheckItemRemark({ ...remarkForm }, () => {
    dialogLoading.value = false;
  });
  dialogLoading.value = false;
  dialogVisible.value = false;
  await nextTick();
  await queryTableDataFn();
};
</script>

<template>
  <div v-loading="loading" class="order-report">
    <div class="order-report-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        :immediate="false"
        :row-num="4"
        :operationSpan="3"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="resetSearchFormHandler"
      />
    </div>
    <div ref="orderReportTableRef" class="order-report-table">
      <commonTable
        ref="commonTableRef"
        indexNeed
        :key="commonTableKey"
        v-model="tableData"
        v-model:loading="loading"
        :pagination="false"
        height="100%"
        :tableCloumns="tableCloumns"
      />
    </div>

    <px-dialog v-model="dialogVisible" title="编辑备注" width="600">
      <px-form v-loading="dialogLoading" :model="remarkForm" label-width="60px">
        <px-form-item label="备注" prop="reportRemark">
          <px-input v-model.trim="remarkForm.reportRemark" type="textarea" rows="6" maxlength="1000" show-word-limit />
        </px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="dialogVisible = false">取消</px-button>
          <px-button type="primary" :loading="dialogLoading" @click="submitFormHandler"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<style lang="scss" scoped>
.order-report {
  width: 100%;
  height: 100%;
  background-color: #fff;

  .order-report-search {
    width: 100%;
  }

  .order-report-table {
    width: 100%;
    height: calc(100% - 50px);
    margin-top: 16px;
  }
}
</style>
